package com.melody.android.logic.database.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.melody.android.MelodyApplication;
import com.melody.android.logic.database.MySQLiteOpenHelper;
import com.melody.android.logic.model.SongList;
import java.util.ArrayList;
import java.util.List;

public class SongListDaoImpl implements SongListDao {

    private final MySQLiteOpenHelper dbHelper = MelodyApplication.sqLiteOpenHelper;

    /**
     * 插入一条SongList记录
     * @param songList SongList实例对象
     */
    @Override
    public void insertSongList(SongList songList) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", songList.getName());
        values.put("num", songList.getNum());

        database.insert("songList", null, values);
        database.close();
    }

    /**
     * 根据id删除一条SongList记录
     * @param SLid 待删除的SongList记录的id
     */
    @Override
    public void deleteSongList(int SLid) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.delete("songList", "SLid = ?", new String[]{String.valueOf(SLid)});
        database.close();
    }

    /**
     * 获取某条SongList记录的id
     * @param songList 待获取id的SongList记录
     * @return 对应SongList记录的id(获取失败返回-1)
     */
    @SuppressLint("Range")
    @Override
    public int getSLidBySongListName(SongList songList) {
        int SLid = -1;
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        Cursor cursor = database.query("songList", new String[]{"SLid"}, "name = ?", new String[]{songList.getName()}, null, null, null);

        if (cursor.moveToFirst()) {
            SLid = cursor.getInt(cursor.getColumnIndex("SLid"));
        }
        cursor.close();
        database.close();

        return SLid;
    }

    /**
     * 获取全部的SongList记录
     * @return songList表中的全部记录
     */
    @Override
    public List<SongList> getAllSongLists() {
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        Cursor cursor = database.query("songList", null, null, null, null, null, null);

        List<SongList> songLists = new ArrayList<>();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") int id = (int) cursor.getLong(cursor.getColumnIndex("SLid"));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
            @SuppressLint("Range") int num = cursor.getInt(cursor.getColumnIndex("num"));

            SongList songList = new SongList(id, name, num);
            songLists.add(songList);
        }
        cursor.close();
        database.close();

        return songLists;
    }

}
